#ifndef __BLOCK_QUEUE_HPP__
#define __BLOCK_QUEUE_HPP__

#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <pthread.h>

template<class T>
class BlockQueue
{
public:
    BlockQueue(int cap):_cap(cap)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_product_cond,nullptr);
        pthread_cond_init(&_consumer_cond,nullptr);
        _consumer_wait_num = 0;
        _productor_wait_num = 0;
    }

    bool Isfull()
    {
        return _block_queue.size() == _cap;
    }

    bool Isempty()
    {
        return _block_queue.empty();
    }

    void Enqueue(const T& in)//生产者入队
    {
        //1.生产先加锁
        pthread_mutex_lock(&_mutex);
        while(Isfull())
        {
            //等待的时候要把锁释放
            _productor_wait_num++;
            pthread_cond_wait(&_product_cond,&_mutex);//哪个队列等待，把锁传过去
             _productor_wait_num--;
        }
        _block_queue.push(std::move(in));
        if(_consumer_wait_num) pthread_cond_signal(&_consumer_cond);
        //pthread_cond_broadcast(&_consumer_cond);
        pthread_mutex_unlock(&_mutex);
    }

    void Pop(T& out)//消费者出队
    {
        //1.消费者先加锁
        pthread_mutex_lock(&_mutex);
        while(Isempty())
        {
            //等待的时候要把锁释放
            _consumer_wait_num++;
            pthread_cond_wait(&_consumer_cond,&_mutex);//哪个队列等待，把锁传过去
            _consumer_wait_num++;
        }
        out = _block_queue.front();
        _block_queue.pop();
        if(_productor_wait_num) pthread_cond_signal(&_product_cond);
        pthread_mutex_unlock(&_mutex);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_product_cond);
        pthread_cond_destroy(&_consumer_cond);
    }

private:
    int _cap;
    std::queue<T> _block_queue;
    pthread_mutex_t _mutex;//保护锁
    pthread_cond_t _product_cond;//专门给生产者提供的条件变量
    pthread_cond_t _consumer_cond;//专门给消费者提供的条件变量
    int _consumer_wait_num;
    int _productor_wait_num;
};

#endif